/*
 * @Author: zwc 6537397+uni-yunApp@user.noreply.gitee.com
 * @Date: 2023-03-15 16:47:32
 * @LastEditors: zwc 6537397+uni-yunApp@user.noreply.gitee.com
 * @LastEditTime: 2023-03-16 14:18:12
 * @FilePath: \project-template\src\api\http.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from "axios";
import type { AxiosInstance, AxiosResponse,AxiosError } from "axios";
import { httpRequestConfig } from './type'
import {toLogin} from '@/utils/common'
import { ElMessage } from 'element-plus'

class Request {
  public instance: AxiosInstance
  // 基础配置，url和超时时间
  public baseConfig: httpRequestConfig = { 
    baseURL:  `${import.meta.env.VITE_APP_BASE_URL}/scrm`, 
    timeout: 60000,
    withCredentials:true,
    headers:{
      'Content-Type': 'application/json; charset=utf-8',
      'x-requested-with': 'XMLHttpRequest',
       sysCode: 'csm'
    }
  };
  constructor(config: httpRequestConfig) {
    this.instance = axios.create(Object.assign(this.baseConfig, config))
    console.log('baseConfig',this.baseConfig)
    // 先创建实例请求拦截器
    this.instance.interceptors.request.use(
      config.interceptors?.requestSuccessInterceptor,
      config.interceptors?.requestErrorInterceptor
    )
    // 先创建实例请求拦截器
    this.instance.interceptors.response.use(
      config.interceptors?.responseSuccessInterceptor,
      config.interceptors?.responseErrorInterceptor
    )
     // 创建全局请求拦截器
     this.instance.interceptors.request.use(
      (config) => {
        console.log('全局请求成功创建的拦截器')
    

        return config
      },
      (err) => {
        console.log('全局请求失败创建的拦截器')
  
        return err
      }
    )
     // 创建全局响应拦截器
     this.instance.interceptors.response.use(
      (response:AxiosResponse) => {
        console.log('全局响应成功创建的拦截器',response)

        return response
      },
      (err:AxiosError) => {
        console.log('全局响应失败创建的拦截器',err)
        ElMessage.error('报错了')
         // 网络不通提示
         if (err.code === 'ERR_NETWORK') {
        ElMessage.error('网络错误，请检查网络!')
        }
        // 网络超时
        if (err.code === 'ECONNABORTED' && err.message.indexOf('timeout') !== -1) {
        ElMessage.error('网络请求超时'!)
        }
        const status = err.response?.status;
     switch (status) {
      case 401:
      // message = "token失效，请重新登录";
       toLogin()
        break;
      case 403:
        break;
      case 404:
        break;
      case 500:
        ElMessage.error('服务器报错了！')
        break;
      default:
       
    }
     
        return err
      }
    )
   
  }
   // 传入的泛型是约束返回值
   request<T>(config: httpRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      // 定制该请求是否加loading。当为传入该参数时，默认为true
      // if (config.showLoading === false) {
      //   this.showLoading = false
      // }
      // 创建单个请求的请求拦截器
      if (config.interceptors?.requestSuccessInterceptor) {
        // 直接调用，然后将处理后的config返回
        config = config.interceptors.requestSuccessInterceptor(config)
      }
      this.instance
        .request<any, T>(config)
        .then((res) => {
       
         // this.showLoading = DEFAULT_LOADING
          // 调用传入的响应拦截器
          if (config.interceptors?.responseSuccessInterceptor) {
            res = config.interceptors.responseSuccessInterceptor(res)
          }
          resolve(res)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
  get<T = any>(url:string,config?: httpRequestConfig<T>) {
    return this.request({url, ...config, method: 'GET' })
  }
  post<T = any>(url:string,data:object,config?: httpRequestConfig<T>) {
    return this.request({ method: 'POST',url,data,...config })
  }
  // delete<T = any>(config: httpRequestConfig<T>) {
  //   return this.request({ ...config, method: 'DELETE' })
  // }
  // patch<T = any>(config: httpRequestConfig<T>) {
  //   return this.request({ ...config, method: 'PATCH' })
  // }
}
export default  Request